﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using _07MindFile.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.IO;
using Newtonsoft.Json;

namespace _07MindFile.Pages
{
    public class MindFileModel : PageModel
    {
        public void OnGet(string path)
        {
            var fileRoot = Path.Combine(Directory.GetCurrentDirectory(), Startup.FileRoot);
            path = Path.Combine(fileRoot, path);
            var mindMap = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(
                System.IO.File.ReadAllText(path));

            MindMapZtree = ZtreeNotRecursion(mindMap.nodes);
        }

        public List<MindMapZtree> ZtreeNotRecursion(List<Nodes> nodes)
        {
            #region 非递归遍历

            Dictionary<string, MindMapZtree> dtoMap = new Dictionary<string, MindMapZtree>();
            foreach (var item in nodes)
            {
                dtoMap.Add(item.id, new MindMapZtree() { name = item.topic, pid = item.parentid });
            }

            List<MindMapZtree> result = new List<MindMapZtree>();
            foreach (var item in dtoMap.Values)
            {
                if (item.pid == null)
                {
                    result.Add(item);
                }
                else
                {
                    if (dtoMap.ContainsKey(item.pid))
                    {
                        dtoMap[item.pid].AddChilrden(item);
                    }
                }
            }
            #endregion

            return result;
        }

        public List<MindMapZtree> MindMapZtree { get; set; }
    }
}